import 'package:dio/dio.dart';
import 'package:mall/core/services/auth.dart';
import 'package:mall/core/providers/view_model.dart';

class UserPasswordUpdateModel extends ViewModel {
  final Auth auth;
  String oldPassword;
  String newPassword;
  String newPasswordConfirm;
  String _errorMessage;

  UserPasswordUpdateModel(this.auth) : super();

  String get errorMessage => _errorMessage;

  Future<ViewState> userPasswordUpdate() async {
    viewState = ViewState.busy;
    try {
      if (oldPassword == null || oldPassword.isEmpty) {
        throw '请输入旧密码';
      }
      if (newPassword == null || newPassword.isEmpty) {
        throw '请输入新密码';
      }
      if (newPasswordConfirm != newPassword) {
        throw '确认密码不一致';
      }
      var params = <String, dynamic>{};
      params['oldPassword'] = oldPassword;
      params['newPassword'] = newPasswordConfirm;
      await auth.userPasswordUpdate(params);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
